package top.jacktgq.cas.unsafe;

import java.lang.reflect.Field;

import sun.misc.Unsafe;
/**
 * 
 * @Title: UnsafeDemo.java 
 * @Package top.jacktgq.cas.unsafe 
 * @Description: 对原子类底层使用的Unsafe类进行测试
 * @author CandyWall   
 * @date 2020年11月3日 下午8:55:56 
 * @version V1.0
 */
public class UnsafeDemo {
	public static void main(String[] args) {
		//Unsafe类不能直接调用然后，jdk做了保护，个人开发者无法直接使用
		//Unsafe unsafe = Unsafe.getUnsafe();
		//这里使用反射的方式进行调用
		Unsafe unsafe = null;
		try {
			Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
			theUnsafe.setAccessible(true);
			unsafe = (Unsafe) theUnsafe.get(null);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(unsafe);
		
		Student stu = new Student();
		System.out.println(stu);
		try {
			// 1、获取字段（域）的偏移地址
			long idOffset = unsafe.objectFieldOffset(Student.class.getDeclaredField("id"));
			long nameOffset = unsafe.objectFieldOffset(Student.class.getDeclaredField("name"));
			//执行cas操作
			System.out.println(unsafe.compareAndSwapInt(stu, idOffset, 0, 1));
			System.out.println(unsafe.compareAndSwapObject(stu, nameOffset, null, "张三"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(stu);
	}
}

class Student {
	volatile int id;
	volatile String name;
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + "]";
	}
}
